/**
 * Created with CLion.
 * Description: 
 * User: cyber
 * Date: 2020-10-16
 * Time: 8:45
 */
#include "LinkedListNode.h"

LinkedListNode::LinkedListNode()
{
    /*[] 创建头节点 */
    head_ = new Node();
}

LinkedListNode::~LinkedListNode()
{
    delete head_;
}

/**
 * @brief 创建节点
 * @param _data 节点数据
 * @param _length 节点个数
 * @return 节点列表
 */
Node * LinkedListNode::CreateNode(const std::string &_data, int _length)
{
    Node *node = new Node(_data);
    Node *temp = node;

    while (--_length > 0) {
        /*[] 创建数据结点 */
        Node *new_node = new Node();
        if (!_data.empty())
            new_node->data = _data;

        temp->next_node = new_node;
        temp = temp->next_node;
    }

    return node;
}

void LinkedListNode::Append(Node *_node)
{
   Node * last_node = Last();
   last_node->next_node = _node;
}

void LinkedListNode::Append(LinkedListNode &_listNode)
{
    Node * last_node = Last();
    last_node->next_node = _listNode.head_->next_node;
}

Node *LinkedListNode::Last()
{
    Node *temp = head_;
    while (nullptr != temp->next_node) {
        temp = temp->next_node;
    }

    return temp;
}

Node *LinkedListNode::Head()
{
    return nullptr != head_->next_node ? head_->next_node : nullptr;
}

Node * LinkedListNode::Find(const string& _node_data)
{
    if(nullptr == head_->next_node)
        return nullptr;

    Node * temp = head_;
    while (nullptr != temp->next_node){
        Node * next = head_->next_node;
        if(next->data.compare(_node_data) == 0)
            return next;
    }

    return nullptr;
}

Node *LinkedListNode::Find(int _pos)
{
    Node * temp = head_->next_node;

    if (_pos > Length() || nullptr == temp)
        return temp;

    while (_pos-- > 0){
        temp = temp->next_node;
    }
    return  temp;
}

bool LinkedListNode::IsEmpty()
{
    if (nullptr == head_->next_node)
        return true;

    return false;
}

void LinkedListNode::Insert(Node *_node, int _pos)
{
    if(_pos > Length())
        return;

    Node * node = Find(_pos);
    if(nullptr == node)
        return;

    Node * temp = node->next_node;
    node->next_node = _node;
    _node->next_node = temp;
}

void LinkedListNode::Delete(const string &_node_data)
{
    Node * node = head_;
    while (nullptr != node->next_node){
        if (node->next_node->data.compare(_node_data) == 0)
            break;
        node = node->next_node;
    }

    Node * temp = node->next_node;
    node->next_node = temp->next_node;
    delete temp;

}

int LinkedListNode::Length()
{
    Node * temp = head_->next_node;
    int i = 0;
    while (nullptr != temp){
        temp = temp->next_node;
        i++;
    }

    return i;
}


